package com.tangji.signaltower.task;

import com.alibaba.fastjson.JSON;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.common.utils.TimeUtils;
import com.jsoniter.output.JsonStream;
import com.tangji.antenna.bean.EventFactory;
import com.tangji.signaltower.bean.MarketDataEntity;
import com.tangji.signaltower.config.FileConfigUtil;
import com.tangji.signaltower.constant.RedisKey;
import com.tangji.signaltower.container.DataContainer;
import com.tangji.signaltower.container.ProductDataContainer;
//import com.tangji.signaltower.disruptor.DisruptorHandler;
import com.tangji.signaltower.disruptor.DisruptorHandler;
import com.tangji.signaltower.enums.ProductEnum;
import com.tangji.signaltower.enums.SubscriptionEnum;
import com.tangji.signaltower.service.dao.dao.ProductMarketDao;
import com.tangji.signaltower.utils.DingTalkPushUtils;
import com.tangji.signaltower.websocket.session.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Amarendar
 * Date: 2020/6/2
 * Time: 下午3:42
 */
@Component
@EnableScheduling
public class BroadcastServiceTaskJob {

    private static final Logger logger = LoggerFactory.getLogger(BroadcastServiceTaskJob.class);

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private ProductMarketDao productMarketDao;

    @Autowired
    private FileConfigUtil fileConfigUtil;

    /**
     * 队列清理
     */
//    @Scheduled(cron = "0 0/30 * * * ?")
    public void run1() {
        logger.info("队列清理");
        for (SubscriptionEnum subscriptionEnum : SubscriptionEnum.values()) {
            Long size = redisClient.zCount(RedisKey.ZSET_BINARY_OPTION_PRODUCT_KEY, 0, 9999999999999d, subscriptionEnum.getType());
            logger.info("集合当前大小,subscription:{},size:{}", subscriptionEnum, size);
            double time1 = System.currentTimeMillis() - 5400 * 1000;//1.5小时前
            Long num = redisClient.zRemoveRangeByScore(RedisKey.ZSET_BINARY_OPTION_PRODUCT_KEY, 0, time1, subscriptionEnum.getType());
            logger.info("清理队列1成功,subscription:{},num:{}", subscriptionEnum, num);
        }
    }

    /**
     * 定时任务一秒推一次数据
     */
//    @Scheduled(cron = "0/2 * * * * ?")
    public void run() {
        long currentTime = System.currentTimeMillis();
        ProductEnum[] values = ProductEnum.values();
        //如果当前循环的时间有效
        for (ProductEnum productEnum : values) {
            logger.info("定时数据推送开始,currentTime:{}", currentTime);
            try {
                DataContainer dataContainer = ProductDataContainer.getDataContainer(productEnum);
                if (dataContainer == null) {
                    logger.error("dataContainer is null error,productEnum:{}", productEnum.getProductCode());
                    continue;
                }

                MarketDataEntity marketDataEntity1 = dataContainer.getLastData();
                if (marketDataEntity1 == null) {
                    logger.error("== getLastData 为空 ==");
                    continue;
                }
                List<MarketDataEntity> historyData = dataContainer.getLastDataList();
                logger.info("== 历史数据 ==,historyData:{}", JsonStream.serialize(historyData));

                MarketDataEntity marketDataEntity = ProductDataContainer.pushDataContainerHashMap.get(productEnum).getFixData(marketDataEntity1);
                marketDataEntity.setMarketTimestamp(currentTime);
                marketDataEntity.setBusinessTime(currentTime);

                MarketDataVo marketDataVo = new MarketDataVo();
                BeanUtils.copyProperties(marketDataEntity, marketDataVo);
                marketDataVo.setHistoryData(historyData);

                dataContainer.resetDataList();

                logger.info("== 推送数据 ==,product:{}", productEnum.getProductCode());
                DisruptorHandler.publish(marketDataVo);
            } catch (Exception e) {
                logger.error("== 定时数据推送开始 异常 ==,productEnum:{}", productEnum.getProductCode(), e);
            }
        }
    }


    private static int btc = 0;

    private static int gbp = 0;

    /**
     * 比特币监控
     */
//    @Scheduled(cron = "0 0/1 * * * ?")
//    public void run2() {
//        {
//            String str = redisClient.get(RedisKey.BINARY_OPTION_PRODUCT_MONITOR_KEY, SubscriptionEnum.BTCUSD.getType());
//            logger.info("比特币行情监控,str:{}", str);
//            if (StringUtils.isEmpty(str)) {
//                return;
//            }
//            MarketDataEntity entity = JSON.parseObject(str, MarketDataEntity.class);
//            long timediff = (System.currentTimeMillis() - entity.getMarketTimestamp()) / 1000;
//            if (timediff > 120 && btc % 5 == 0) {
//                logger.error("比特币行情异常,触发重启,str:{}", str);
//                PoNettyClient.getInst().getChannel().close();
//                logger.error("比特币行情异常,渠道通道关闭等待重启,str:{}", str);
//                if (!fileConfigUtil.isServerTest()) {
//                    DingTalkPushUtils.pushTextMessageAtPart("https://oapi.dingtalk.com/robot/send?access_token=7cdbd52a7736ac9e9dcbcd2de59442897d8d46d4655ef87aba943493bcacf6a8", "比特币行情异常", new ArrayList<>());
//                }
//                btc++;
//            } else {
//                logger.info("比特币行情延迟,str:{},timediff:{}", str, timediff);
//            }
//        }
//
//        {
//            String str = redisClient.get(RedisKey.BINARY_OPTION_PRODUCT_MONITOR_KEY, SubscriptionEnum.GBP_USD.getType());
//            logger.info("英镑美元行情监控,str:{}", str);
//            if (StringUtils.isEmpty(str)) {
//                return;
//            }
//            MarketDataEntity entity = JSON.parseObject(str, MarketDataEntity.class);
//            long timediff = (System.currentTimeMillis() - entity.getMarketTimestamp()) / 1000;
//            int week = 999;
//            try {
//                week = DateUtil.dayForWeek(DateUtil.getDate(new Date()));
//            } catch (Exception e) {
//            }
//            if (timediff > 120 && week <= 5) {
//                if (gbp % 10 == 0) {
//                    logger.error("英镑美元行情异常,触发重启,str:{}", str);
//                    ForexPoNettyClient.getInst().getChannel().close();
//                    logger.error("英镑美元行情异常,渠道通道关闭等待重启,str:{}", str);
//                    if (!fileConfigUtil.isServerTest()) {
//                        DingTalkPushUtils.pushTextMessageAtPart("https://oapi.dingtalk.com/robot/send?access_token=7cdbd52a7736ac9e9dcbcd2de59442897d8d46d4655ef87aba943493bcacf6a8", "汇率行情异常", new ArrayList<>());
//                    }
//                }
//                gbp++;
//            } else {
//                logger.info("英镑美元行情延迟,str:{},timediff:{}", str, timediff);
//            }
//        }
//    }

    /**
     * 在线用户数监控
     */
    @Scheduled(cron = "0 0/20 * * * ?")
    public void onlineReport() {
        List<String> report = SessionFactory.getSessionDataReport();
        StringBuilder sb = new StringBuilder();
        for (String s : report) {
            sb.append(s);
            sb.append("\n");
        }
        logger.info("在线用户数报告:{}", report.toString());
        if (!fileConfigUtil.isServerTest()
                && Integer.parseInt(DateUtil.getDate(new Date(), "HH")) >= 8
                && Integer.parseInt(DateUtil.getDate(new Date(), "HH")) <= 23) {
            DingTalkPushUtils.pushTextMessageAtPart(sb.toString(), new ArrayList<>());
        }
    }


    public static void main(String[] args) {
//        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Calcutta"));

        long l = System.currentTimeMillis();

        System.err.println(1111);
    }

}
